/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.search;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import bw.util.*;

public class SearchServlet extends HttpServlet
{

    public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
        throws ServletException, IOException 
    {
        SearchManager manager = SearchManager.getInstance();

        String query = req.getParameter( "q" );

        SearchQuery searchQuery = manager.getDefaultQuery();

        int codeIdentifier = -1;
        if ( ( codeIdentifier = query.indexOf( ":" ) ) > -1 )
        {
            //get the code
            String code = query.substring( 0, codeIdentifier );
            //log.write( "SearchServlet: Got the code: " + code );

            //remove code from the query
            query = query.substring( codeIdentifier + 1 ).trim();
            //log.write( "SearchServlet: Got the query: " + query );
            
            //if the code is bogus then this will return the default
            searchQuery = manager.getSearchQuery( code );

            if ( searchQuery instanceof CommandQuery )
            {
                ( (CommandQuery) searchQuery ).setRequest( req );
            }
        }

        String redirectURL = searchQuery.getSearchURL( query );
        if ( redirectURL.startsWith( "/" ) )
        {
            //use a requestDispatcher to forward the request
            RequestDispatcher dispatcher = req.getRequestDispatcher( redirectURL );
            dispatcher.forward( req, res );
        }
        else
        {
            res.sendRedirect( redirectURL );
        }
    }
}